package com.crm.jdy.controller.ceshi.clearfield;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class JsonReturnHandler implements HandlerMethodReturnValueHandler {
     List<ResponseBodyAdvice<Object>> advices = new ArrayList<>();

     @Override
     public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
                                   NativeWebRequest webRequest) throws Exception {
          mavContainer.setRequestHandled(true);
          for (int i = 0; i < advices.size(); i++) {
               ResponseBodyAdvice<Object> ad = advices.get(i);
               if (ad.supports(returnType, null)) {
                    returnValue = ad.beforeBodyWrite(returnValue, returnType, MediaType.APPLICATION_JSON_UTF8, null,
                                                          new ServletServerHttpRequest(webRequest.getNativeRequest(HttpServletRequest.class)),
                              new ServletServerHttpResponse(webRequest.getNativeResponse(HttpServletResponse.class)));
               }
          }

     }

     @Override
     public boolean supportsReturnType(MethodParameter returnType) {
          boolean hasJSONAnno = returnType.getMethodAnnotation(JSON.class) != null
                    || returnType.getMethodAnnotation(JSONS.class) != null;
          return hasJSONAnno;
     }
 
}
